import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:provider/provider.dart';
import 'package:reorderables/reorderables.dart';
import 'package:test01/okhttp_test/pojo/serach_pojo.dart';
import 'package:test01/okhttp_test/provider/searchwords.dart';
import 'package:test01/okhttp_test/util/request_http.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    ///禁止程序横屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp, //只能纵向
      DeviceOrientation.portraitDown, //只能纵向
    ]);

    return MaterialApp(
      home: SearchPage(),
    );
  }
}

class SearchPage extends StatefulWidget {
  const SearchPage({Key key}) : super(key: key);

  @override
  SearchPageState createState() => SearchPageState();
}

class SearchPageState extends State<SearchPage> {

  List <String> recent_search=[];
  ///热门词汇
  List<HotWordsList> hotwords_search = [];

  ///热门话题
  List<HotToppicList> hottopic_search = [];

  ///TextFiled搜索输入框——控制器
  TextEditingController textfile_controller = TextEditingController();

  ///判断清空按钮是否显示
  bool isShowClearn = false;

  ///初始化拖拽框
  List<Widget> items=[];




  @override
  void initState() {
    ///初始化最近搜索数据
    context.read<IsFollow>().readData();
    ///获取热门话题
    hotTopic();
    ///获取热门词汇
    hotWords();


    super.initState();
  }

  ///获取热门词汇
  hotWords() async {
    hotwords_search = await hotWordsApi("/appuser/web/feed/getHotWords");
    ///初始化拖拽框
    items=List.generate(hotwords_search.length, (i) {
      return Container(
        height: 24,
        // padding: EdgeInsets.only(left: 8,right: 8),
        //动态获取文字宽度
        width: hotwords_search.length != 0
            ? (hotwords_search[i].name.length.toDouble() * 12) + 16
            : 0,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colors.grey.withOpacity(0.2),
          borderRadius: BorderRadius.all(Radius.circular(5)),
        ),
        child: Text(
          '${hotwords_search[i].name}',
          style: TextStyle(fontSize: 12),
        ),
      );
    });
    setState(() {

    });
    print("获取数据：-------------${hotwords_search.toString()}-----------------");
  }

  ///获取热门话题
  hotTopic() async {
    hottopic_search =
        await hotTopicApi(4, "/appuser/web/topic/getRecommendTopic");
    setState(() {

    });
  }





  @override
  Widget build(BuildContext context) {
    void onReorder(int oldIndex, int newIndex) {
      Widget row = items[oldIndex];
      setState(() {
        items.removeAt(oldIndex);
        items.insert(newIndex, row);
      });
    }

    return Scaffold(
        body: SingleChildScrollView(
      child: Column(
        children: <Widget>[
          ///状态栏高度
          SizedBox(
            height: MediaQueryData.fromWindow(window).padding.top,
          ),

          ///搜索栏
          Container(
            height: 44,
            margin: EdgeInsets.only(left: 16),
            child: Row(
              children: <Widget>[
                Container(
                  width: MediaQuery.of(context).size.width - 76,
                  decoration: BoxDecoration(
                    color: Colors.grey.withOpacity(0.2),
                    borderRadius: BorderRadius.all(Radius.circular(3)),
                  ),
                  height: 32,
                  child: Row(
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(left: 13.5),
                        child: Icon(
                          Icons.zoom_out_rounded,
                          size: 18,
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(left: 7.5),
                        width: MediaQuery.of(context).size.width - 154,
                        child: TextField(
                          ///控制器
                          controller: textfile_controller,

                          ///输入框获取数据操作
                          onChanged: (value) {
                            setState(() {
                              if (value.length != 0) {
                                isShowClearn = true;
                              } else {
                                isShowClearn = false;
                              }
                            });
                          },

                          ///键盘的操作数据
                          onSubmitted: (value) {
                            if (value != null) {
                              context.read<IsFollow>().setRecentSearch(value);
                            }
                          },
                          textInputAction: TextInputAction.done,
                          decoration: InputDecoration.collapsed(
                            hintText: '搜索用户话题、课程、动态',
                            hintStyle: TextStyle(color: Colors.grey),
                          ),
                        ),
                      ),
                      isShowClearn
                          ? GestureDetector(
                              onTap: () {
                                setState(() {
                                  textfile_controller.clear();
                                  isShowClearn=false;
                                });
                              },
                              child: Container(
                                margin: EdgeInsets.only(left: 13.5),
                                child: Icon(
                                  Icons.add_circle_outline_outlined,
                                  size: 18,
                                ),
                              ),
                            )
                          : Container(),
                    ],
                  ),
                ),
                GestureDetector(
                  onTap: (){
                    Navigator.pop(context);
                  },
                  child: Container(
                    margin: EdgeInsets.only(left: 12),
                    child: Text(
                      "取消",
                      style: TextStyle(fontSize: 16),
                    ),
                  ),
                ),

              ],
            ),
          ),

          ///最近搜索
          context.watch<IsFollow>().recent_search.length == 0
              ? Container()
              : Container(
                  height: 48,
                  margin: EdgeInsets.only(top: 12),
                  child: Row(
                    children: <Widget>[
                      SizedBox(
                        width: 16,
                      ),
                      Text(
                        "最近搜索",
                        style: TextStyle(fontSize: 15),
                      ),
                      Spacer(),
                      GestureDetector(
                        onTap: () {
                          print("删除了------------------");
                          context.read<IsFollow>().cleanRecentSearch();
                        },
                        child: Icon(
                          Icons.delete,
                          size: 14,
                        ),
                      ),
                      SizedBox(
                        width: 16,
                      )
                    ],
                  ),
                ),

          ///最近搜索列表框
          ///最近搜索
          context.watch<IsFollow>().recent_search.length == 0
              ? Container()
              : Container(
                  height: 23,
                  margin: EdgeInsets.only(right: 16),
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    reverse: false,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                        height: 16,
                        alignment: Alignment.center,
                        margin: EdgeInsets.only(left: 16),
                        padding: EdgeInsets.only(left: 8, right: 8),
                        decoration: BoxDecoration(
                          color: Colors.grey.withOpacity(0.2),
                          borderRadius: BorderRadius.all(Radius.circular(5)),
                        ),
                        child: Text(
                          "${context.watch<IsFollow>().recent_search[index]}",
                          style: TextStyle(fontSize: 12),
                        ),
                      );
                    },
                    itemCount: context.watch<IsFollow>().recent_search.length,
                  ),
                ),

          ///热门搜索
          hotwords_search.length == 0
              ? Container()
              : Container(
                  height: 48,
                  margin: EdgeInsets.only(top: 18),
                  child: Row(
                    children: <Widget>[
                      SizedBox(
                        width: 16,
                      ),
                      Text(
                        "热门搜索",
                        style: TextStyle(fontSize: 15),
                      ),
                    ],
                  ),
                ),

          ///热门搜索列表框
          Container(
            width: MediaQuery.of(context).size.width - 32,
            child: ReorderableWrap(
              spacing: 16,
              runSpacing: 16,
              crossAxisAlignment: WrapCrossAlignment.start,
                children: items,
                onReorder: onReorder,
                onNoReorder: (int index) {
                  debugPrint('移动的index:$index');
                },
                onReorderStarted: (int index) {
                  //this callback is optional
                  debugPrint('拖动时index:$index');

                }

              // List.generate(hotwords_search.length, (i) {
              //   return Container(
              //     height: 24,
              //     // padding: EdgeInsets.only(left: 8,right: 8),
              //     //动态获取文字宽度
              //     width: hotwords_search.length != 0
              //         ? (hotwords_search[i].name.length.toDouble() * 12) + 16
              //         : 0,
              //     alignment: Alignment.center,
              //     decoration: BoxDecoration(
              //       color: Colors.grey.withOpacity(0.2),
              //       borderRadius: BorderRadius.all(Radius.circular(5)),
              //     ),
              //     child: Text(
              //       '${hotwords_search[i].name}',
              //       style: TextStyle(fontSize: 12),
              //     ),
              //   );
              // }),
                ),
            ),
          ///热门课程
          Container(
            height: 48,
            margin: EdgeInsets.only(top: 24),
            child: Row(
              children: <Widget>[
                SizedBox(
                  width: 16,
                ),
                Text(
                  "热门课程",
                  style: TextStyle(fontSize: 15),
                ),
              ],
            ),
          ),

          ///热门课程列表框
          Container(
            width: MediaQuery.of(context).size.width - 32,
            child: Wrap(
              spacing: 16,
              runSpacing: 16,
              crossAxisAlignment: WrapCrossAlignment.start,
              children: List.generate(4, (i) {
                return Container(
                  decoration: BoxDecoration(
                    color: Colors.grey.withOpacity(0.2),
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                  ),
                  width: (MediaQuery.of(context).size.width - 48) / 2,
                  height: 48,
                  child: Row(
                    children: <Widget>[
                      ///判断热门课程颜色
                      i > 2
                          ? Container(
                              child: Text(
                                "${i + 1}",
                                style: TextStyle(
                                    fontSize: 14,
                                    color: Color.fromRGBO(153, 153, 153, 1)),
                              ),
                            )
                          : Container(
                              child: Text(
                                "${i + 1}",
                                style: TextStyle(
                                    fontSize: 14,
                                    color: Color.fromRGBO(255, 64, 89, 1)),
                              ),
                            ),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            margin: EdgeInsets.only(left: 10),
                            child: Text(
                              "胸背训练教学动作",
                              style: TextStyle(fontSize: 14),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          Container(
                            width:
                                ((MediaQuery.of(context).size.width - 48) / 2) -
                                    40,
                            margin: EdgeInsets.only(left: 10, top: 2),
                            child: Text(
                              "信息描述信息描述信息描述信息描述信息",
                              style: TextStyle(
                                  fontSize: 12,
                                  color: Color.fromRGBO(153, 153, 153, 1)),
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                            ),
                          )
                        ],
                      )
                    ],
                  ),
                );
              }),
            ),
          ),

          ///热门话题
          hottopic_search.length == 0
              ? Container()
              : Container(
                  height: 48,
                  margin: EdgeInsets.only(top: 24),
                  child: Row(
                    children: <Widget>[
                      SizedBox(
                        width: 16,
                      ),
                      Text(
                        "热门话题",
                        style: TextStyle(fontSize: 15),
                      ),
                    ],
                  ),
                ),

          ///热门话题框
          hottopic_search.length == 0
              ? Container()
              : Container(
                  height: 170,
                  margin: EdgeInsets.only(left: 8),
                  child: Swiper(
                    scrollDirection: Axis.horizontal,
                    // 横向
                    itemCount: hottopic_search.length,
                    // 数量
                    autoplay: false,
                    // 自动翻页
                    itemBuilder: (BuildContext context, int index) {
                      ///列表框
                      return Stack(
                        children: <Widget>[
                          Container(
                            width: MediaQuery.of(context).size.width - 38,
                            height: 144,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(2)),
                              border: new Border.all(
                                  width: 1,
                                  color: Colors.black.withOpacity(0.1)),

                              ///设置边框阴影
                              boxShadow: [
                                BoxShadow(
                                    color: Color.fromRGBO(0, 0, 0, 1)
                                        .withOpacity(0.85),
                                    offset: Offset(0, 3.0), //阴影x轴偏移量
                                    blurRadius: 5.5, //阴影模糊程度
                                    spreadRadius: -4.5 //阴影扩散程度
                                    )
                              ],

                              ///设置渐变色
                              gradient: LinearGradient(
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                                colors: [
                                  Color.fromRGBO(243, 243, 243, 1),
                                  Colors.white,
                                ],
                              ),
                            ),
                            child: Image(
                              image: AssetImage("assets/icon/bg_topic.png"),
                            ),
                          ),
                          Container(
                            height: 144,
                            width: MediaQuery.of(context).size.width - 38,
                            child: Column(
                              children: <Widget>[
                                Row(
                                  children: <Widget>[
                                    Container(
                                      margin:
                                          EdgeInsets.only(left: 16, top: 19),
                                      child: Icon(
                                        Icons.add_comment_outlined,
                                        size: 20,
                                      ),
                                    ),
                                    Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Container(
                                          margin: EdgeInsets.only(
                                              left: 18.5, top: 9),
                                          child: Text(
                                            "#${hottopic_search[index].name}",
                                            style: TextStyle(fontSize: 15),
                                          ),
                                        ),
                                        Container(
                                          margin: EdgeInsets.only(
                                              left: 18.5, top: 2),
                                          child: Text(
                                            "${hottopic_search[index].feedCount}条动态",
                                            style: TextStyle(
                                                fontSize: 15,
                                                color: Color.fromRGBO(
                                                    153, 153, 153, 1)),
                                          ),
                                        )
                                      ],
                                    ),
                                  ],
                                ),

                                ///热门话题列表框
                                Container(
                                  height: 74,
                                  width: MediaQuery.of(context).size.width - 38,
                                  margin: EdgeInsets.only(top: 12),
                                  padding:
                                      EdgeInsets.only(left: 6.5, right: 6.5),
                                  child: Container(
                                    child: ListView.builder(
                                      physics:
                                          const NeverScrollableScrollPhysics(),
                                      scrollDirection: Axis.horizontal,
                                      reverse: false,
                                      itemBuilder:
                                          (BuildContext context, int i) {
                                        ///圆角图片
                                        return Container(
                                          width: (MediaQuery.of(context)
                                                      .size
                                                      .width -
                                                  22 -
                                                  16 -
                                                  20 -
                                                  7 * 3) /
                                              4,
                                          margin: EdgeInsets.only(
                                              left: 3.5, right: 3.5),
                                          decoration: BoxDecoration(
                                            image: DecorationImage(
                                              fit: BoxFit.cover,
                                              image: NetworkImage(
                                                  hottopic_search[index]
                                                      .pics[i]
                                                      .coverUrl),
                                            ),
                                            borderRadius: BorderRadius.all(
                                                Radius.circular(8.0)),
                                            color: Colors.redAccent,
                                          ),
                                        );
                                      },
                                      itemCount:
                                          hottopic_search[index].pics.length > 4
                                              ? 4
                                              : hottopic_search[index]
                                                  .pics
                                                  .length,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      );
                    },
                    viewportFraction: 0.8,
                    // 当前视窗展示比例 小于1可见上一个和下一个视窗
                    layout: SwiperLayout.STACK,
                    itemWidth: MediaQuery.of(context).size.width - 32,
                    scale: 0.8,
                    itemHeight: 144,
                  ),
                ),
        ],
      ),
    ));
  }
}
